<?php
/**
 * Created by PhpStorm.
 * User: jswei
 * Date: 2018/5/3
 * Time: 14:06
 */
namespace app\first\model;

use think\Model;

class OrderList extends Model{
    protected $autoWriteTimestamp = false;

    /**
     * @param array $where
     * @param string $order
     * @param int $limit
     * @param string $filed
     * @param bool $flag
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList($where=[],$order='create_time desc',$limit=10,$filed='openid',$flag=true){
        $list = $this
            ->field($filed,$flag)
            ->with(['user'=>function($query){
                $query->field('id,account,nickname');
            }])
            ->where($where)
            ->order($order)
            ->paginate($limit);
        return $list;
    }

    /**
     * @param $title
     * @param $mid
     * @param $out_trade_no
     * @param $total_amount
     * @param $type
     * @param $pay_type
     * @param $days
     * @param string $openid
     * @param null $out
     * @return bool
     */
    public function addNew($title,$mid,$out_trade_no,$total_amount,$type,$pay_type,$days,$openid='',&$out=null){
        $data = [
            'title'=>$title,
            'mid'=>$mid,
            'out_trade_no'=>$out_trade_no,
            'type'=>$type,
            'pay_type'=>$pay_type,
            'days'=>$days,
            'openid'=>$openid,
            'total_amount'=>$total_amount,
            'create_time'=>time()
        ];
        $valid = new \app\first\validate\RechargeList();
        if(!$valid->check($data)){
            $out = $valid->getError();
            return false;
        }
        $id = $this->insertGetId($data);
        if(!$id){
            $out = '订单创建失败';
            return false;
        }
        $this->isUpdate(true)->save([
            'id'=>$id,
            'out_trade_no'=> $out_trade_no
        ]);
        $out = [
            'order_id'=>intval($id),
            'title'=>$title,
            'out_trade_no'=>$out_trade_no
        ];
        return true;
    }

    public function user(){
        return $this->hasOne('member','id','mid');
    }
}